package com.talkweb.citypickerview.style.citylist;

import com.example.library.github.promeg.pinyinhelper.Pinyin;
import com.talkweb.citypickerview.ResourceTable;
import com.talkweb.citypickerview.style.citylist.bean.CityInfoBean;
import com.talkweb.citypickerview.style.citylist.sortlistview.*;
import com.talkweb.citypickerview.style.citylist.utils.CityListLoader;
import com.talkweb.citypickerview.style.citylist.widget.CleanableEditView;
import com.talkweb.citypickerview.utils.TextUtils;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.ListContainer;
import ohos.agp.components.Text;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static com.talkweb.citypickerview.Constant.RESULT_OK;

public class CityListSelectAbility extends Ability {

    private HiLogLabel logLabel = new HiLogLabel(HiLog.LOG_APP, 0x1234, CityListSelectAbility.class.getSimpleName());
    CleanableEditView mCityTextSearch;

    Text mCurrentCityTag;

    Text mCurrentCity;

    Text mLocalCityTag;

    Text mLocalCity;

    ListContainer sortListView;

    Text mTvDialog;

    SideBar mSidebar;

    Image imgBack;

    public SortAdapter adapter;

    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;

    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;

    private List<CityInfoBean> cityListInfo = new ArrayList<>();

    private CityInfoBean cityInfoBean = new CityInfoBean();

    //startActivityForResult flag
    public static final int CITY_SELECT_RESULT_FRAG = 0x0000032;

    public static List<CityInfoBean> sCityInfoBeanList = new ArrayList<>();
    private List<SortModel> sourceDateList = new ArrayList<SortModel>();

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_ability_city_list_select);
        initView();
        initData();

        setCityData(CityListLoader.getInstance().getCityListData());
        initList();

    }

    private void initData() {
        //实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();
        pinyinComparator = new PinyinComparator();
        mSidebar.setTextView(mTvDialog);
    }

    private void initView() {
        mCityTextSearch = (CleanableEditView) findComponentById(ResourceTable.Id_cityinputtext);
        mCurrentCityTag = (Text) findComponentById(ResourceTable.Id_currentcitytag);
        mCurrentCity = (Text) findComponentById(ResourceTable.Id_currentcity);
        mLocalCityTag = (Text) findComponentById(ResourceTable.Id_localcitytag);
        mLocalCity = (Text) findComponentById(ResourceTable.Id_localcity);
        sortListView = (ListContainer) findComponentById(ResourceTable.Id_country_lvcountry);
        mTvDialog = (Text) findComponentById(ResourceTable.Id_tv_dialog);
        mSidebar = (SideBar) findComponentById(ResourceTable.Id_sidrbar);
        imgBack = (Image) findComponentById(ResourceTable.Id_imgback);
        imgBack.setClickedListener(v -> terminateAbility());

    }

    private void setCityData(List<CityInfoBean> cityList) {
        cityListInfo = cityList;
        if (cityListInfo == null) {
            return;
        }

        sourceDateList.addAll(filledData(cityList));
        // 根据a-z进行排序源数据
        Collections.sort(sourceDateList, pinyinComparator);
    }

    /**
     * 为ListView填充数据
     *
     * @return
     */
    private List<SortModel> filledData(List<CityInfoBean> cityList) {
        List<SortModel> mSortList = new ArrayList<SortModel>();
        for (int i = 0; i < cityList.size(); i++) {
            CityInfoBean result = cityList.get(i);
            if (result != null) {
                SortModel sortModel = new SortModel();
                String cityName = result.getName();
                //汉字转换成拼音
                if (!TextUtils.isEmpty(cityName) && cityName.length() > 0) {
                    String pinyin = Pinyin.toPinyin(cityName.substring(0, 1), "");

                    if (!TextUtils.isEmpty(pinyin)) {
                        sortModel.setName(cityName);
                        String sortString = pinyin.substring(0, 1).toUpperCase();
                        // 正则表达式，判断首字母是否是英文字母
                        if (sortString.matches("[A-Z]")) {
                            sortModel.setSortLetters(sortString.toUpperCase());
                        } else {
                            sortModel.setSortLetters("#");
                        }
                        mSortList.add(sortModel);
                    } else {
                        HiLog.info(logLabel, "citypicker_log", "null,cityName:-> " + cityName + "       pinyin:-> " + pinyin);
                    }
                }
            }
        }
        return mSortList;
    }

    private void initList() {
        adapter = new SortAdapter(CityListSelectAbility.this, sourceDateList);
        sortListView.setItemProvider(adapter);

        //设置右侧触摸监听
        mSidebar.setOnTouchingLetterChangedListener(s -> {
            //该字母首次出现的位置
            int position = adapter.getPositionForSection(s.charAt(0));
            if (position != -1) {
                sortListView.scrollTo(position);
            }
        });

        sortListView.setItemClickedListener((listContainer, component, position, l) -> {
            String cityName = ((SortModel) adapter.getItem(position)).getName();
            cityInfoBean = CityInfoBean.findCity(cityListInfo, cityName);
            Intent intent = new Intent();
            intent.setParam("cityinfo", cityInfoBean);
            setResult(RESULT_OK, intent);
            terminateAbility();
        });

        //根据输入框输入值的改变来过滤搜索
        mCityTextSearch.addTextObserver((s, start, before, count) -> {
            //当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
            filterData(s);
        });

    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    private void filterData(String filterStr) {
        List<SortModel> filterDateList = new ArrayList<SortModel>();

        if (TextUtils.isEmpty(filterStr)) {
            filterDateList = sourceDateList;
        } else {
            filterDateList.clear();
            for (SortModel sortModel : sourceDateList) {
                String name = sortModel.getName();
                if (name.contains(filterStr) || characterParser.getSelling(name).startsWith(filterStr)) {
                    filterDateList.add(sortModel);
                }
            }
        }

        // 根据a-z进行排序
        Collections.sort(filterDateList, pinyinComparator);
        adapter.updateListView(filterDateList);
    }

}
